Download 320*480px JPEG Image collection For Testing

Bonrix Dynamic QR Code Scanner Display (DQR-111) WiFi Model


Postman ScreenShot:

Javascript Code:

Curl Command:


    curl --location 'http://IP Address/upload' \
      --form 'file=@"filepath"'
      
      replace IP Address for according to connected display ip
      replace Filepath with actual jpeg file location
      
  

Java Example:


    import java.io.DataOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.net.HttpURLConnection;
    import java.net.URL;

    public class UploadFile {

        public static void main(String[] args) {
            String targetURL = "http://192.168.29.173/upload";
            String filePath = "C:/Users/Lenovo/Desktop/WhatsApp Image 2024-07-16 at 4.13.57 PM.jpeg";
            String boundary = "===" + System.currentTimeMillis() + "===";

            HttpURLConnection connection = null;
            DataOutputStream outputStream = null;
            FileInputStream fileInputStream = null;

            try {
                File file = new File(filePath);
                URL url = new URL(targetURL);
                connection = (HttpURLConnection) url.openConnection();
                connection.setDoOutput(true);
                connection.setDoInput(true);
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
                connection.setRequestProperty("Connection", "Keep-Alive");
                connection.setRequestProperty("Cache-Control", "no-cache");

                outputStream = new DataOutputStream(connection.getOutputStream());

                // Add file part
                outputStream.writeBytes("--" + boundary + "\r\n");
                outputStream.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n");
                outputStream.writeBytes("Content-Type: application/octet-stream\r\n");
                outputStream.writeBytes("\r\n");

                fileInputStream = new FileInputStream(file);
                int bytesRead;
                byte[] buffer = new byte[4096];
                while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                outputStream.writeBytes("\r\n");

                // Add ending boundary
                outputStream.writeBytes("--" + boundary + "--\r\n");
                outputStream.flush();

                // Get the response
                int responseCode = connection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    System.out.println("File uploaded successfully.");
                } else {
                    System.out.println("File upload failed with response code: " + responseCode);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (fileInputStream != null) {
                    try {
                        fileInputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (outputStream != null) {
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (connection != null) {
                    connection.disconnect();
                }
            }
        }
    }

  

C#.NET Example:


    HttpUploadFile(ip, filePath);

    public static string HttpUploadFile(string url, string filePath)
           {
               try
               {
                   if (url.ToLower().Contains("https://"))
                   {
                       ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;
                   }
                   string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
                   HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                   request.Method = "POST";
                   request.ContentType = "multipart/form-data; boundary=" + boundary;
                  
                   // Start building the request body
                   StringBuilder sb = new StringBuilder();
                   sb.AppendLine("--" + boundary);
                   sb.AppendLine("Content-Disposition: form-data; name=\"file\"; filename=\"" + System.IO.Path.GetFileName(filePath) + "\"");
                   sb.AppendLine("Content-Type: application/octet-stream");
                   sb.AppendLine();
   
                   // Convert the string to a byte array
                   byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sb.ToString());
   
                   // Read the file data
                   byte[] fileData = File.ReadAllBytes(filePath);
   
                   // Create the footer
                   byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
   
                   long length = postHeaderBytes.Length + fileData.Length + boundaryBytes.Length;
                   request.ContentLength = length;
   
                   using (Stream requestStream = request.GetRequestStream())
                   {
                       // Write the string header
                       requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
                       // Write the file data
                       requestStream.Write(fileData, 0, fileData.Length);
                       // Write the footer
                       requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
                   }
   
                   try
                   {
                       using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                       using (Stream responseStream = response.GetResponseStream())
                       using (StreamReader reader = new StreamReader(responseStream))
                       {
                           string result = reader.ReadToEnd();
                           return result;
                       }
                   }
                   catch (WebException ex)
                   {
                       using (Stream responseStream = ex.Response.GetResponseStream())
                       using (StreamReader reader = new StreamReader(responseStream))
                       {
                           string errorText = reader.ReadToEnd();
                           return errorText;
                       }
                   }
                   catch(Exception ex)
                   {
                       return ex.Message;
                   }
               }
               catch(Exception ex)
               {
                   return ex.Message;
               }
           }

  

Python Example:


    import http.client
    import mimetypes
    from codecs import encode

    conn = http.client.HTTPConnection("192.168.29.173")
    dataList = []
    boundary = 'wL36Yn8afVp8Ag7AmP8qZ0SA4n1v9T'
    dataList.append(encode('--' + boundary))
    dataList.append(encode('Content-Disposition: form-data; name=file; filename={0}'.format('C:\\Users\\Dell\\Downloads\\w.jpeg')))

    fileType = mimetypes.guess_type('C:\\Users\\Dell\\Downloads\\w.jpeg')[0] or 'application/octet-stream'
    dataList.append(encode('Content-Type: {}'.format(fileType)))
    dataList.append(encode(''))

    with open('C:\\Users\\Dell\\Downloads\\w.jpeg', 'rb') as f:
      dataList.append(f.read())
    dataList.append(encode('--'+boundary+'--'))
    dataList.append(encode(''))
    body = b'\r\n'.join(dataList)
    payload = body
    headers = {
      'Content-type': 'multipart/form-data; boundary={}'.format(boundary) 
    }
    conn.request("POST", "/upload", payload, headers)
    res = conn.getresponse()
    data = res.read()
    print(data.decode("utf-8"))

  

node.js Example:


    const http = require('http');
    const fs = require('fs');
    const path = require('path');

    const boundary = 'wL36Yn8afVp8Ag7AmP8qZ0SA4n1v9T';
    const filePath = 'C:\\Users\\tanma\\Desktop\\image.jpeg'; // Update the file path here
    const fileName = path.basename(filePath);
    const fileType = 'image/jpeg';

    const options = {
      hostname: '192.168.29.173',
      port: 80,
      path: '/upload',
      method: 'POST',
      headers: {
        'Content-Type': multipart/form-data; boundary=${boundary},
        'Content-Length': null
      }
    };

    // Create the multipart/form-data body
    const postData = [];
    postData.push(--${boundary}\r\n);
    postData.push(Content-Disposition: form-data; name="file"; filename="${fileName}"\r\n);
    postData.push(Content-Type: ${fileType}\r\n\r\n);

    const fileStream = fs.readFileSync(filePath);
    postData.push(fileStream);
    postData.push(\r\n--${boundary}--\r\n);

    // Calculate the total length of the body
    const body = Buffer.concat(postData.map(item => (typeof item === 'string' ? Buffer.from(item) : item)));
    options.headers['Content-Length'] = body.length;

    const req = http.request(options, (res) => {
      let data = '';

      res.on('data', (chunk) => {
        data += chunk;
      });

      res.on('end', () => {
        console.log(data);
      });
    });

    req.on('error', (e) => {
      console.error(Problem with request: ${e.message});
    });

    // Write the body to the request
    req.write(body);
    req.end();

  

VB.NET Example:


    
    Public Function HttpUploadFile(ByVal url As String, ByVal filePath As String) As String
    Try
    url = "http://" & url & "/upload"
        If url.ToLower().Contains("https://") Then
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 Or SecurityProtocolType.Tls11 Or SecurityProtocolType.Tls Or SecurityProtocolType.Ssl3
        End If

        Dim boundary As String = "----------------------------" & DateTime.Now.Ticks.ToString("x")
        Dim request As HttpWebRequest = CType(WebRequest.Create(url), HttpWebRequest)
        request.Method = "POST"
        request.ContentType = "multipart/form-data; boundary=" & boundary

        ' Start building the request body
        Dim sb As New StringBuilder()
        sb.AppendLine("--" & boundary)
        sb.AppendLine("Content-Disposition: form-data; name=""file""; filename=""" & Path.GetFileName(filePath) & """")
        sb.AppendLine("Content-Type: application/octet-stream")
        sb.AppendLine()

        ' Convert the string to a byte array
        Dim postHeaderBytes As Byte() = Encoding.UTF8.GetBytes(sb.ToString())

        ' Read the file data
        Dim fileData As Byte() = File.ReadAllBytes(filePath)

        ' Create the footer
        Dim boundaryBytes As Byte() = Encoding.ASCII.GetBytes(vbCrLf & "--" & boundary & "--" & vbCrLf)

        Dim length As Long = postHeaderBytes.Length + fileData.Length + boundaryBytes.Length
        request.ContentLength = length

        Using requestStream As Stream = request.GetRequestStream()
            ' Write the string header
            requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length)
            ' Write the file data
            requestStream.Write(fileData, 0, fileData.Length)
            ' Write the footer
            requestStream.Write(boundaryBytes, 0, boundaryBytes.Length)
        End Using

        Try
            Using response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
                Using responseStream As Stream = response.GetResponseStream()
                    Using reader As New StreamReader(responseStream)
                        Dim result As String = reader.ReadToEnd()
                        Return result
                    End Using
                End Using
            End Using
        Catch ex As WebException
            Using responseStream As Stream = ex.Response.GetResponseStream()
                Using reader As New StreamReader(responseStream)
                    Dim errorText As String = reader.ReadToEnd()
                    Return errorText
                End Using
            End Using
        Catch ex As Exception
            Return ex.Message
        End Try
    Catch ex As Exception
        Return ex.Message
    End Try
    End Function